import axios from 'axios'

// API配置 - 读写分离架构
const API_CONFIG = {
  READ_API: 'http://39.96.200.62:8411', // 读API - 查询操作
  WRITE_API: 'http://39.96.200.62:8511', // 写API - 新增、修改、删除操作
  ENDPOINTS: {
    LIST: '/api/PregnancyExamination/list',
    CREATE: '/api/PregnancyExamination/create',
    UPDATE: '/api/PregnancyExamination/update',
    DELETE: '/api/PregnancyExamination/delete',
    BATCH_DELETE: '/api/PregnancyExamination/batch-delete',
    DETAIL: '/api/PregnancyExamination'
  }
}

// 读API实例 - 用于查询操作
const readApi = axios.create({
  baseURL: API_CONFIG.READ_API,
  timeout: 10000
})

// 写API实例 - 用于新增、修改、删除操作
const writeApi = axios.create({
  baseURL: API_CONFIG.WRITE_API,
  timeout: 10000
})

// 为API实例添加Token
readApi.interceptors.request.use(config => {
  const token = localStorage.getItem('Token') || localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

writeApi.interceptors.request.use(config => {
  const token = localStorage.getItem('Token') || localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 种母妊检查询列表接口 - 读操作
export function getPregnancyExaminationList(params: {
  pageIndex: number
  pageSize: number
  startDate?: string
  endDate?: string
  earTag?: string
  responsiblePerson?: string
  pregnancyResult?: string
  fetusCount?: string | number
  excludeDeleted?: boolean // 是否排除已删除的数据
}) {
  // 默认排除已删除的数据
  const queryParams = { ...params, excludeDeleted: params.excludeDeleted !== false }
  return readApi.get(API_CONFIG.ENDPOINTS.LIST, { params: queryParams })
}

// 添加种母妊检记录 - 写操作
export function addPregnancyExamination(data: any) {
  console.log('提交新增数据:', data)
  
  // 确保日期格式正确
  if (data.pregnancy_check_date && !data.pregnancy_check_date.includes('T')) {
    data.pregnancy_check_date = `${data.pregnancy_check_date}T00:00:00`
  }
  
  return writeApi.post(API_CONFIG.ENDPOINTS.CREATE, data)
}

// 获取种母妊检详情 - 读操作
export function getPregnancyExaminationDetail(id: string) {
  console.log(`获取种母妊检详情, id: ${id}`)
  return readApi.get(`${API_CONFIG.ENDPOINTS.DETAIL}/${id}`)
}

// 更新种母妊检记录 - 写操作
export function updatePregnancyExamination(data: any) {
  console.log('提交更新数据:', data)
  
  // 确保日期格式正确
  if (data.pregnancy_check_date && !data.pregnancy_check_date.includes('T')) {
    data.pregnancy_check_date = `${data.pregnancy_check_date}T00:00:00`
  }
  
  // 确保ExaminationId是整数类型，并使用原始名称
  if (data.examination_id) {
    data.ExaminationId = parseInt(data.examination_id)
    // 删除小写的examinationId以避免混淆
    delete data.examination_id
  } else if (data.examinationId) {
    data.ExaminationId = parseInt(data.examinationId)
    // 删除小写的examinationId以避免混淆
    delete data.examinationId
  }
  
  // 确保数值字段类型正确
  if (data.fetus_count !== undefined) {
    data.fetus_count = Number(data.fetus_count)
  }
  
  if (data.gestation_days !== undefined) {
    data.gestation_days = Number(data.gestation_days)
  }
  
  // 确保所有必填字段都有值
  if (!data.ear_tag) {
    console.warn('ear_tag字段为空')
  }
  if (!data.current_pen) {
    console.warn('current_pen字段为空')
  }
  if (!data.current_stall) {
    console.warn('current_stall字段为空')
  }
  if (!data.transfer_pen) {
    console.warn('transfer_pen字段为空')
  }
  if (!data.transfer_stall) {
    console.warn('transfer_stall字段为空')
  }
  if (!data.pregnancy_method) {
    console.warn('pregnancy_method字段为空')
  }
  if (!data.pregnancy_result) {
    console.warn('pregnancy_result字段为空')
  }
  if (!data.responsible_person) {
    console.warn('responsible_person字段为空')
  }
  if (!data.document_number) {
    console.warn('document_number字段为空')
  }
  if (!data.record_type) {
    // 默认设置为常规
    data.record_type = "常规"
  }
  
  console.log('最终提交的数据:', data)
  return writeApi.post(API_CONFIG.ENDPOINTS.UPDATE, data)
}

// 删除种母妊检记录 - 写操作
export function deletePregnancyExamination(id: string | number, operator: string = 'admin', remark: string = '普通删除') {
  console.log(`删除种母妊检记录, id: ${id}`)
  // 确保ID是整数类型
  const examinationId = typeof id === 'string' ? parseInt(id) : id
  return writeApi.post(`${API_CONFIG.ENDPOINTS.DELETE}`, { 
    ExaminationId: examinationId, 
    Operator: operator, 
    Remark: remark 
  })
}

// 批量删除种母妊检记录 - 写操作
export function batchDeletePregnancyExamination(ids: (string | number)[], operator: string = 'admin', remark: string = '批量删除') {
  console.log(`批量删除种母妊检记录, ids: ${ids.join(',')}`)
  // 确保所有ID都是整数类型
  const examinationIds = ids.map(id => typeof id === 'string' ? parseInt(id) : id)
  return writeApi.post(API_CONFIG.ENDPOINTS.BATCH_DELETE, { 
    ExaminationIds: examinationIds,
    Operator: operator,
    Remark: remark
  })
} 